<template>
  <div class='app-container'>
    <div class='button-container'>
      <z-dialog :show.sync="show"></z-dialog>
      <el-button class='filter-item' type='primary' @click='openEditWeAppDialog(null,true)' icon='edit'>新增</el-button>
    </div>
    <div>
      <!-- 表格 -->
      <el-table ref="RoleTable" @selection-change="onSelectionChanged" :data="GridPageList" v-loading.body="gridDataIsLoading" element-loading-text="数据加载中..." border fit highlight-current-row>

        <el-table-column align="center" label='序号' width="150">
          <template scope="scope">
            {{scope.$index + 1}}
          </template>
        </el-table-column>

        <el-table-column label="微信APPID" width="200">
          <template scope="scope">
            {{scope.row.basicinfo.appid}}
          </template>
        </el-table-column>

        <el-table-column label="微信APP名称" width="200">
          <template scope="scope">
            {{scope.row.basicinfo.appname}}
          </template>
        </el-table-column>
        <el-table-column label="商户首页显示方式" width="200">
          <template scope="scope">
            <el-tag type='primary' close-transition v-if="scope.row.basicinfo.apphometype==0">店铺列表
            </el-tag>
            <el-tag type='success' close-transition v-if="scope.row.basicinfo.apphometype==1">热卖展示
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="单笔订单最大可付款" width="200">
          <template scope="scope">
            {{scope.row.rainfo.maxorderpaymy>0?scope.row.rainfo.maxorderpaymy+'元':'无上限'}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template scope="scope">
            <el-button icon="edit" size="small" type="primary" @click=openEditWeAppDialog(scope.row,false)>编辑</el-button>
            <el-button icon="setting" size="small" @click=setDefaultGoods(scope.row)>设置店铺默认下属货品</el-button>
            <el-button icon="delete" type="danger" size="small" @click="deleteApp(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div v-show="!gridDataIsLoading" class="pagination-container">
      <el-pagination @size-change="onPageSizeChanged" @current-change="onPageNoChanged" :current-page.sync="paginationConfig.currentQueryPage" :page-sizes="[10,20,30, 50]" :page-size="paginationConfig.selectedPageSize" layout="total, sizes, prev, pager, next, jumper" :total="dataCount">
      </el-pagination>
    </div>
    <!-- <el-dialog title='新增微信app' :visible.sync='editAppDialogOpend'>
      <el-form :model="editingApp" ref="appForm" :rules="rules">
        <el-form-item label='微信APPID' prop="appid">
          <el-input v-model='editingApp.appid' placeholder="请输入微信APPID" :disabled="!editDialogIsNewMode"></el-input>
        </el-form-item>
        <el-form-item label='微信APP名称' prop="appname">
          <el-input v-model='editingApp.appname' placeholder="请输入微信APP名称"></el-input>
        </el-form-item>
         <el-form-item label='Crm网关' prop="crmapigetway">
          <el-input v-model='editingApp.crmapigetway' placeholder="请输入crm卡网关"></el-input>
        </el-form-item>
        <el-form-item label="默认城市" prop="cityadcode">          
            <el-select v-model='selectedProvince' placeholder="请选择" class="input" @change="emtyCity">
                <el-option v-for="(item,index) in mapCategorys" :key="index" :label="item.name" :value="index">
                </el-option>
            </el-select>
            <el-select  v-model='editingApp.cityadcode' placeholder="请选择" class="input">
                <el-option v-for="(item,index) in citys" :key="item.adcode" :label="item.name" :value="item.adcode">
                </el-option>
            </el-select>
        </el-form-item>         
        <el-form-item prop="crmqrcodeurl">    
          <div class="lable-span">领卡二维码</div>     
          <div class="qrcode_img">           
            <el-upload :show-file-list="false" class="qrcode-uploader" :action="uploadUrl" :on-success="uploadQrcodeSuccesss">
              <img v-if="editingApp.crmqrcodeurl!=''" :src="editingApp.crmqrcodeurl" class="qrcode"> </img>
              <div v-else class="deaultqrcode"> </div>
            </el-upload>
          </div>
        </el-form-item>       
        <el-form-item label="首页展示类型" prop="apphometype">
          <el-select v-model="editingApp.apphometype" placeholder="请选择">
            <el-option label="店铺列表" :value="0"> </el-option>
            <el-option label="热卖展示" :value="1"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="首页展示店铺" prop="mainshop" v-show="editingApp.apphometype==1">
          <el-select v-model="editingApp.mainshopid" filterable placeholder="请选择">
            <el-option v-for="shop in shopSelectList" :key="shop.shopid" :label="shop.shopname" :value="shop.shopid">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="editingApp.apphometype==0">
          <div class="lable-span">首页跑马灯图片</div>
          <div>
            <ul class="img-wrapper">
              <li v-for="(pic,index) in editingApp.swipepics" :key="index">
                <div class="img-container">
                  <img :src="pic" class="avatar"> </img>
                </div>
                <div align="center">
                  <i class="fa fa-times-circle" style="font-size: 24px;color: red;" @click="deleteJpg(index)"></i>
                </div>
              </li>
            </ul>
            <el-upload class="upload-file" :action="uploadUrl" :on-success="uploadSuccess" :show-file-list="false">
              <el-button type="primary">上传
                <i class="el-icon-upload el-icon--right"></i>
              </el-button>
            </el-upload>
          </div>
        </el-form-item>        
        <el-form-item label='每单最大付款限额' prop="maxorderpaymy">
          <el-input-number v-model="editingApp.maxorderpaymy" :min="0" :controls="true" :step="100"></el-input-number>
        </el-form-item>
        <el-form-item label='配送范围(km)' prop="sendrange">
          <el-input-number v-model="editingApp.sendrange" :min="0" :controls="true"></el-input-number>
        </el-form-item>
        <el-form-item>
          <div class="lable-span">快速备注</div>
          <ul>
            <li v-for="(info,index) in editingApp.fixedremarks" :key="index" style="margin-top:12px;margin-bottom:12px;">
              <el-input placeholder="请输入备注" v-model="info.remarkstext">
                <el-button slot="append" icon="close" @click='removeRemarks(index)'></el-button>
              </el-input>
            </li>
          </ul>
          <el-button type="primary" icon="plus" plain size="small" @click='addRemarks'>添加</el-button>
        </el-form-item>
      </el-form>
      <div slot='footer' class='dialog-footer'>
        <el-button type='primary' @click='handleEditAppSubmit'>确定</el-button>
        <el-button @click='editAppDialogOpend = false'>取消</el-button>
      </div>
    </el-dialog> -->

    <!-- 指定商户默认货品 -->
    <el-dialog title='指定商户默认货品' :visible.sync='defaultGoodDialogOpend'>
      <div class="good-transfer">
        <el-transfer v-model="selecteGoods" :titles="['未选货品', '已选货品']" :props="{ key: 'gsid', label: 'gsname'}" :data="allGoods"></el-transfer>
      </div>
      <div slot='footer' class='dialog-footer'>
        <el-button type='primary' @click='handleSetGoodsubmit'>确定</el-button>
        <el-button @click='defaultGoodDialogOpend = false'>取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ZDialog from './editWeAppDialog';
import axios from "axios";
import { Utils } from "@/utils/utils.js";
export default {
  name: "wechatappset",
  data() {
    // const validateappexist = (rule, value, callback) => {
    //   if (this.editDialogIsNewMode) {
    //     this.$http
    //       .get("/WechatMallOss/App/GetAppByAppId", {
    //         params: {
    //           appid: value
    //         }
    //       })
    //       .then(response => {
    //         if (response.data.isSuccess) {
    //           if (response.data.appinfo == null) {
    //             callback();
    //           } else {
    //             callback(new Error("app已存在"));
    //           }
    //         } else {
    //           callback(new Error("验证遇见未知错误!"));
    //         }
    //       })
    //       .catch(err => {
    //         callback(err);
    //       });
    //   } else {
    //     callback();
    //   }
    // };
    return {
      // 表格数据源
      gridDataSource: [],
      // 当前分页数据开始index
      startIndex: 0,
      // 当前分页数据结束index
      endIndex: 0,
      currentSelectedRow: null,
      gridDataIsLoading: false,
      // 编辑窗体的状态是否是新增状态
      editDialogIsNewMode: true,
      // 分页配置
      paginationConfig: { selectedPageSize: 10, currentQueryPage: 0 },
      // 编辑层是否显示
      editAppDialogOpend: false,
      //  正在编辑的model
      editingApp: {
        appid: "",
        appname: "",
        apphometype: 0,
        maxorderpaymy: 0,
        sendrange: 0,
        swipepics: [],
        cityname: "",
        citycenter: "",
        cityadcode: "",
        mainshopid: 0,
        crmapigetway: "",
        crmqrcodeurl: "",
        fixedremarks: []
      },
      // 编辑的app 下属门店列表
      shopSelectList: [],
      // 表单验证规则
      // rules: {
      //   appid: [
      //     { required: true, trigger: "blur", message: "微信APPID必填" },
      //     {
      //       type: "string",
      //       max: 50,
      //       trigger: "blur",
      //       message: "微信APPID必须小于50个字"
      //     },
      //     { trigger: "blur", validator: validateappexist }
      //   ],
      //   appname: [
      //     { required: true, trigger: "blur", message: "微信APP名称必填" },
      //     {
      //       type: "string",
      //       max: 50,
      //       trigger: "blur",
      //       message: "微信APP名称必须小于50个字"
      //     }
      //   ],
      //   crmapigetway: [
      //     { required: true, trigger: "blur", message: "crm卡网关必填" }
      //   ],
      //   cityadcode: [{ required: true, trigger: "blur", message: "默认定位城市必选" }],
      //   crmqrcodeurl: [{ required: true, trigger: "blur", message: "领卡二维码必选！" }]
      // },
      // 指定货品
      selecteGoods: [],
      allGoods: [],
      defaultGoodDialogOpend: false,
      mapCategorys: [],
      selectedProvince: 0,
      citys: [],
      show: false
    };
  },
  methods: {
    /**
     * 刷新数据
     */
    refreshData() {
      this.gridDataIsLoading = true;
      this.$http
        .all([
          this.$http.get("/WechatMallOss/App/GetApps").then(response => {
            if (response.data.isSuccess) {
              this.gridDataSource = response.data.appinfos;
            }
          }),
          this.$http.get("/WechatMallOss/Good/GetAllGoods").then(response => {
            if (response.data.isSuccess) {
              this.allGoods = [];
              response.data.goods.forEach(good => {
                this.allGoods.push({
                  gsid: good.basic.gsid,
                  gsname: good.basic.gsname
                });
              });
            }
          })
          // this.$http.get("/WechatMallOss/App/GetAllCitys").then(response => {
          //   if (response.data.isSuccess) {
          //     this.mapCategorys = response.data.mapCategorys;
          //   }
          // })
        ])
        .then(() => {
          this.gridDataIsLoading = false;
        })
        .catch(() => {
          this.gridDataIsLoading = false;
        });
    },
    computeDataIndex(pageNo, pageSize) {
      this.startIndex = pageSize * (pageNo - 1) + 1;
      this.endIndex = this.startIndex + pageSize;
    },
    // uploadQrcodeSuccesss(res, file) {
    //   if (res.isSuccess && res.savedObjects) {
    //     this.editingApp.crmqrcodeurl =
    //       axios.defaults.baseURL +
    //       "/img/get?img=" +
    //       res.savedObjects[0].fileName;
    //   }
    // },
    // uploadSuccess(res, file) {
    //   if (res.isSuccess && res.savedObjects) {
    //     this.editingApp.swipepics.push(
    //       axios.defaults.baseURL +
    //         "/img/get?img=" +
    //         res.savedObjects[0].fileName
    //     );
    //   }
    // },
    // openEditWeAppDialog(row, isnew) {
    //   this.editDialogIsNewMode = isnew;

    //   if (isnew) {
    //     this.shopSelectList = [];
    //     this.editingApp.appid = "";
    //     this.editingApp.appname = "";
    //     this.editingApp.sendrange = 5;
    //     this.editingApp.swipepics = [];
    //     this.editingApp.mainshopid = 0;
    //     this.editingApp.apphometype = 0;
    //     this.editingApp.maxorderpaymy = 0;
    //     this.editingApp.crmapigetway = "";
    //     this.editingApp.crmqrcodeurl = "";
    //     this.editingApp.cityname = "";
    //     this.editingApp.citycenter = "";
    //     this.editingApp.cityadcode = "";
    //     this.editAppDialogOpend = true;
    //   } else {
    //     /* 初始化级联下拉数据 */
    //     this.selectedProvince = this.mapCategorys.findIndex(province => {
    //       if (province.citys) {
    //         let cityindex = province.citys.findIndex(city => {
    //           return city.adcode === row.basicinfo.cityadcode;
    //         });
    //         return cityindex !== -1;
    //       }
    //       return false;
    //     });

    //     if (this.selectedProvince !== -1) {
    //       this.citys = this.mapCategorys[this.selectedProvince].citys;
    //     }
    //     this.editingApp.appid = row.basicinfo.appid;
    //     this.editingApp.appname = row.basicinfo.appname;
    //     this.editingApp.apphometype = row.basicinfo.apphometype;
    //     this.editingApp.sendrange = row.basicinfo.sendrange;
    //     this.editingApp.swipepics = row.swipepics;
    //     this.editingApp.mainshopid = row.basicinfo.mainshopid;
    //     this.editingApp.maxorderpaymy = row.rainfo.maxorderpaymy;
    //     this.editingApp.crmapigetway = row.basicinfo.crmapigetway;
    //     this.editingApp.crmqrcodeurl = row.basicinfo.crmqrcodeurl;
    //     this.editingApp.cityname = row.basicinfo.cityname;
    //     this.editingApp.citycenter = row.basicinfo.citycenter;
    //     this.editingApp.cityadcode = row.basicinfo.cityadcode;
    //     this.$http
    //       .get("/WechatMallOss/Shop/GetShopsByAppId", {
    //         params: {
    //           appid: row.basicinfo.appid
    //         }
    //       })
    //       .then(response => {
    //         if (response.data.isSuccess) {
    //           this.shopSelectList = [];
    //           response.data.shops.forEach(shop => {
    //             this.shopSelectList.push({
    //               shopid: shop.shopId,
    //               shopname: shop.name
    //             });
    //           });
    //           this.editAppDialogOpend = true;
    //         }
    //       });
    //   }
    // },
    openEditWeAppDialog() {
      this.show = true;
    },

    /**
     * 分页变化
     */
    onPageSizeChanged(size) {
      this.paginationConfig.selectedPageSize = size;
      this.computeDataIndex(this.paginationConfig.currentQueryPage, size);
    },
    onPageNoChanged(page) {
      this.paginationConfig.currentQueryPage = page;
      this.computeDataIndex(page, this.paginationConfig.selectedPageSize);
    },
    /**
     * 表格selectchanged
     */
    onSelectionChanged(select) {
      this.currentSelectedRow = select;
    },
    setDefaultGoods(row) {
      this.currentSelectedRow = row;
      console.log(this.currentSelectedRow.basicinfo.appid);
      let appid = this.currentSelectedRow.basicinfo.appid;
      if (appid) {
        this.$http
          .get("/WechatMallOss/Good/GetGoodsByAppid", {
            params: {
              appid: appid
            }
          })
          .then(response => {
            if (response.data.isSuccess) {
              this.selecteGoods.splice(0, this.selecteGoods.length);
              response.data.goods.forEach(good => {
                this.selecteGoods.push(good.basic.gsid);
              });
              this.defaultGoodDialogOpend = true;
            }
          });
      }
    },
    /**
     * 指定下属货品
     */
    handleSetGoodsubmit() {
      let appid = this.currentSelectedRow.basicinfo.appid;
      if (appid) {
        this.$http
          .post("/WechatMallOss/App/SaveAppGsRelationShip", {
            appid: appid,
            gsids: this.selecteGoods
          })
          .then(response => {
            if (response.data.isSuccess) {
              this.$message({
                message: "指定物品成功!",
                type: "success"
              });
              this.defaultGoodDialogOpend = false;
            }
          })
          .catch(() => {
            this.$message({
              message: "数据保存失败!",
              type: "error"
            });
          });
      }
    },
    // /**
    //  * 提交新增app表单
    //  */
    // handleEditAppSubmit() {
    //   this.$refs.appForm.validate(valid => {
    //     if (valid) {
    //       let cityindex = this.citys.findIndex(item => {
    //         return item.adcode === this.editingApp.cityadcode;
    //       });
    //       let city = this.citys[cityindex];
    //       console.log(city);
    //       if (city) {
    //         this.editingApp.cityname = city.name;
    //         this.editingApp.citycenter = city.center;
    //       }

    //       this.$http
    //         .post("/WechatMallOss/App/SaveAppInfo", this.editingApp)
    //         .then(response => {
    //           if (response.data.isSuccess) {
    //             this.$message({
    //               message: "保存成功!",
    //               type: "success"
    //             });
    //             if (response.data.appinfo) {
    //               let updateIndex = this.gridDataSource.findIndex(app => {
    //                 if (app.basicinfo) {
    //                   return (
    //                     app.basicinfo.appid ===
    //                     response.data.appinfo.basicinfo.appid
    //                   );
    //                 } else {
    //                   return false;
    //                 }
    //               });
    //               if (updateIndex > -1) {
    //                 this.gridDataSource.splice(
    //                   updateIndex,
    //                   1,
    //                   response.data.appinfo
    //                 );
    //               } else {
    //                 this.gridDataSource.push(response.data.appinfo);
    //               }
    //             }
    //             this.editAppDialogOpend = false;
    //           } else {
    //             this.$message({
    //               message: "数据提交出现错误,请稍后重试!",
    //               type: "error"
    //             });
    //           }
    //         })
    //         .catch(() => {
    //           this.$message({
    //             message: "数据提交出现错误,请稍后重试!",
    //             type: "error"
    //           });
    //         });
    //     } else {
    //       return false;
    //     }
    //   });
    // },
    /**
     * 删除app
     */
    deleteApp(index, row) {
      let appid = row.basicinfo.appid;
      if (appid) {
        this.$confirm("删除app信息后,此公众号微商城将不能使用, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.$http
            .delete("/WechatMallOss/App/deleteApp", {
              params: {
                appid: appid
              }
            })
            .then(response => {
              if (response.data.isSuccess) {
                this.gridDataSource.splice(index, 1);
                this.$message({
                  message: "删除成功!",
                  type: "success"
                });
              }
            });
        });
      }
    },
    /**
     * 删除图片
     */
    deleteJpg(index) {
      this.editingApp.swipepics.splice(index);
    },
    emtyCity() {
      this.editingApp.cityadcode = "";
    },
    // 移除快速备注信息
    removeRemarks(index) {
      this.editingApp.fixedremarks.splice(index, 1);
    },
    /** 添加快速备注信息  */
    addRemarks() {
      this.editingApp.fixedremarks.push({
        remarkstext: ""
      });
    }
  },
  watch: {
    selectedProvince(value) {
      if (this.mapCategorys[value]) {
        let citys = this.mapCategorys[value].citys;
        this.citys = citys;
      } else {
        this.citys = [];
      }
    }
  },
  created() {
    this.refreshData();
  },
  components: {
    ZDialog
  },
  computed: {
    uploadUrl() {
      let jwt = Utils.GetLocalData("zillionossjwt");
      return axios.defaults.baseURL + "/img/upload?token=" + jwt;
    },
    GridPageList() {
      if (this.gridDataSource && this.gridDataSource.length > 0) {
        if (this.startIndex > 0 && this.endIndex > 0) {
          return this.gridDataSource.slice(
            this.startIndex - 1,
            this.endIndex - 1
          );
        } else {
          return [];
        }
      } else {
        return [];
      }
    },
    dataCount() {
      if (this.gridDataSource) {
        return this.gridDataSource.length;
      } else {
        return 0;
      }
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss">
.lable-span {
  font-size: 14px;
  color: #48576a;
  font-weight: 700;
}
.qrcode_img {
  margin-bottom: 12px;
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  .qrcode-uploader .el-upload:hover {
    border-color: #20a0ff;
  }
  .qrcode-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .qrcode {
    width: 178px;
    height: 178px;
  }
  .deaultqrcode {
    width: 130px;
    height: 130px;
    background-repeat: no-repeat;
    border: none;
    background-image: url("./defaultqrcode.png");
  }
}
.img-wrapper {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 100%;
  .img-container {
    margin: 5px;
    width: 120px;
    height: 70px;
    box-sizing: border-box;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    .el-upload:hover {
      border-color: #20a0ff;
    }
    img {
      width: 120px;
      height: 70px;
    }
  }
}

.close {
  margin: 3px;
  width: 30px;
  height: 30px;
  align-items: center;
}
</style>
